package com.whosly.foundationdb.study.config.jetty.handler;

import com.whosly.foundationdb.study.config.jetty.WebFluxServerResponseWriter;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 *  处理 WebFilter 抛出的异常
 */
@Slf4j
public class WebErrorWebExceptionHandler implements ErrorWebExceptionHandler {

    private WebFluxServerResponseWriter webFluxServerResponseWriter;

    private static final int LIMIT_LEN = 128;

    private String errorPageUrl;

    public void setErrorPageUrl(String url) {
        this.errorPageUrl = url;
    }

    public void setWebFluxServerResponseWriter(WebFluxServerResponseWriter webFluxServerResponseWriter) {
        this.webFluxServerResponseWriter = webFluxServerResponseWriter;
    }

    @Override
    public Mono<Void> handle(ServerWebExchange serverWebExchange, Throwable throwable) {
        ServerHttpRequest request = serverWebExchange.getRequest();

        log.error("处理URI:{}请求发生异常:{},", request.getURI(), throwable);

        // 输出JSON字符串内容
        ControllerResponse controllerResponse = new ControllerResponse();
        String message = StringUtils.substring(throwable.getMessage(), 0, LIMIT_LEN);
        controllerResponse.setCode(ControllerResponse.ERROR);
        controllerResponse.setMessage(message);
        return webFluxServerResponseWriter.write(
                serverWebExchange,
                controllerResponse.toString(),
                throwable
        );
    }

//    @Override
//    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
//
//        ServerHttpResponse response = exchange.getResponse();
//        response.setStatusCode(HttpStatus.OK);
//
//        ResultVo vo = ResultVo.error(ex.getMessage());
//
//        DataBuffer buff = response.bufferFactory()
//                .allocateBuffer().write(JSONUtil.toJsonStr(vo).getBytes());
//        //基于流形式
//        response.getHeaders().setContentType(MediaType.APPLICATION_STREAM_JSON);
//        return response.writeAndFlushWith(Mono.just(ByteBufMono.just(buff)));
//    }
//
    @Data
    private static class ControllerResponse {

        public static final Long ERROR = 500L;

        private Long code;
        private String message;
    }

}
